package com.mk.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mk.entity.User;
import com.mk.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类，定时下线用户，让用户重新登录
 */
@Component
@RequiredArgsConstructor
public class UserLoginTask {

    private final UserMapper userMapper;

    /**
     * 处理让用户下线的方法
     */
    @Scheduled(cron = "${task.loginScheduled.cron}") //每分钟触发一次
    public void login() {
        LocalDateTime time = LocalDateTime.now().plusHours(-3);

        List<User> userList = userMapper.selectList(new LambdaQueryWrapper<User>()
                .eq(User::getStatus, User.ONLINE)
                .le(User::getOnlineTime, time));

        if (userList != null && userList.size() > 0) {
            for (User user : userList) {
                user.setStatus(User.NOT_ONLINE);
                user.setOfflineTime(LocalDateTime.now());
                userMapper.updateById(user);
            }
        }
    }
}
